package org.acme.hibernate.orm.panache;

import io.quarkus.runtime.StartupEvent;
import io.vertx.mutiny.mysqlclient.MySQLPool;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import org.eclipse.microprofile.config.inject.ConfigProperty;

@ApplicationScoped
public class DBInit {

    private final MySQLPool client;

    private final boolean schemaCreated;

    public DBInit(MySQLPool client, @ConfigProperty(name = "myapp.schema.create", defaultValue = "true") boolean schemaCreated) {
        this.client = client;
        this.schemaCreated = schemaCreated;
    }

    void onStart(@Observes StartupEvent ev) {
        if (schemaCreated) {
            initDb();
        }
    }

    private void initDb() {
        client.query("DROP table if exists fruits").execute()
                .flatMap(r -> client.query("create table fruits (id int  primary key auto_increment,name text not null) ").execute())
                .flatMap(r -> client.query("INSERT INTO fruits (name) VALUES ('Kiwi')").execute())
                .flatMap(r -> client.query("INSERT INTO fruits (name) VALUES ('Durian')").execute())
                .flatMap(r -> client.query("INSERT INTO fruits (name) VALUES ('Pomelo')").execute())
                .flatMap(r -> client.query("INSERT INTO fruits (name) VALUES ('Lychee')").execute())
                .await().indefinitely();
    }

}
